package projectManagementServer;


import ch.randelshofer.quaqua.util.Methods;
import ch.randelshofer.quaqua.*;
import ch.randelshofer.*;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;

import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import messages.*;

public class ServerGUI extends JPanel implements ActionListener, WindowListener{
	//JPanel
	JPanel leftPanel;
	JPanel centerPanel;
	JPanel rightPanel;
	JTabbedPane selectionTabPane;

	JPanel panelDiscussion;

	static DefaultListModel<String> projectListModel;
	static JList<String> projectList;

	static DefaultListModel<String> usersListModel;
	static JList<String> usersList;

	static ActionGUI acGUI;
	ActionConnection acConnection;

	JButton btnStart;
	JButton btnStop;

	static JPanel panelProfile;
	static String pictureName;
	static JTextField textName;
	static ProfileButton profileBtn;

	AccessDatabase allData;
	static ArrayList<Project> allProject;
	static ArrayList<Member> allMember;
	static ArrayList<Files> allFiles;
	static ArrayList<MemberProject> allMemProj;

	static ArrayList<Project> ongoingProject;
	static ArrayList<Project> completedProject;

	static JButton btnOnGoing;
	JButton btnCompleted;

	ServerLogic serverLogic;

	public ServerGUI() throws Exception {
		setPreferredSize(new Dimension(1000, 600));
		setLayout(null);

		allData = new AccessDatabase();
		allProject = allData.getAllProject();
		allMember = allData.getAllMember();
		allMemProj = allData.getAllMemProj();
		allFiles = allData.getAllFiles();

		ongoingProject = new ArrayList<>();
		completedProject = new ArrayList<>();
		//projMemStat= allData.g;

		//ProjectMemberStatus projMemStat = new
		//allProjMemStat = new ArrayList<>();

		/**for(int i=0; i<allProject.size(); i++){
			for(int x=0; x<allMemProj.size(); x++){
				int occ = 0;
				if(allProject.get(i).getProjectName().equalsIgnoreCase(allMemProj.get(x).getProjectName())){
					if(allProjMemStat.isEmpty()){
						allProjMemStat.add(new ProjectMemberStatus(allProject.get(i).getProjectName(), allProject.get(i).getProjectLeader(), allProject.get(i).getStatus()));
					}else{
						for(int y=0; y<allProjMemStat.size(); y++){
							if(allProject.get(i).getProjectName().equalsIgnoreCase(allProjMemStat.get(y).getProjectName())){
								for(int z=0; z<allMember.size(); z++){
									if(allMemProj.get(x).getMember().equalsIgnoreCase(allMember.get(z).getUserName())){
										allProjMemStat.get(y).addMember(allMember.get(z));
										System.out.println("added member");
									}else{}
								}
							}else{}
						}
						allProjMemStat.add(new ProjectMemberStatus(allProject.get(i).getProjectName(), allProject.get(i).getProjectLeader(), allProject.get(i).getStatus()));
						for(int a=0; a<allProjMemStat.size(); a++){
							if(allProjMemStat.get(a).getProjectName().equalsIgnoreCase(allProject.get(i).getProjectName())){
								occ++;
							}
						}
						if(occ > 1){
							for(int ad=0; ad<allProjMemStat.size(); ad++){
								if(allProjMemStat.get(0).getProjectName().equalsIgnoreCase(allProject.get(i).getProjectName())){
									allProjMemStat.remove(i);
									System.out.println("removed");
								}
							}

						}
					}

				}else{}

			}
		}
		//System.out.println(allMemProj.get(0).getProjectName());
		//System.out.println(allProjMemStat.size());
		for(int ix = 0; ix<allProjMemStat.size(); ix++){
			System.out.println(allProjMemStat.get(ix).getProjectName());
			System.out.println(allProjMemStat.get(ix).getProjectLeader());
		}
		System.out.println(allProjMemStat.get(0).getAllMember().size());
		/**for(int iy=0; iy<allProjMemStat.get(0).getAllMember().size(); iy++){
			System.out.println(allProjMemStat.get(0).getAllMember().get(iy).getUserName());
		}**/
		//System.out.println(allProjMemStat.get(0).getProjectName());
		//System.out.println(allProjMemStat.get(0).getProjectLeader());
		//System.out.println(allProjMemStat.get(1).getProjectName());
		//System.out.println(allProjMemStat.get(1).getProjectLeader());
		//System.out.println(allProjMemStat.get(2).getProjectName());
		//System.out.println(allProjMemStat.get(2).getProjectLeader());
		/**for(int i=0 ; i<allMemProj.size(); i++){
			if(allProject.get(i).getProjectName().equalsIgnoreCase(allMemProj.get(i).getProjectName()))
		}**/

		acGUI = new ActionGUI();
		acConnection = new ActionConnection();

		pictureName = "profile/profile.png";

		leftPanel = new JPanel();
		leftPanel.setBounds(5, 61, 178, 528);
		add(leftPanel);
		leftPanel.setLayout(null);

		addProfilePanel();
		addOptionPanel();

		centerPanel = new JPanel();
		centerPanel.setBackground(new Color(0, 0, 51));
		centerPanel.setBounds(187, 61, 603, 528);
		centerPanel.setOpaque(true);
		add(centerPanel);
		centerPanel.setLayout(null);

		addDiscussionPanel();
		addMsgPanel();
		addSendMsgPanel();

		rightPanel = new JPanel();
		rightPanel.setBounds(793, 61, 203, 528);
		add(rightPanel);
		rightPanel.setLayout(null);

		addCurrentProjectPanel();
		addSelectionTab();
		addProjectTab();
		addUsersTab();


		JFrame frame = new JFrame();
		frame.getContentPane().add(this);
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setLocationRelativeTo(null);


	}

// LEFT PANEL ----------------------------------------------------------------------------------------------------------------------------------------
	public void addProfilePanel(){
		panelProfile = new JPanel();
		panelProfile.setBorder(new TitledBorder(null, "PROFILE", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panelProfile.setBounds(10, 11, 158, 212);
		panelProfile.setLayout(null);

		profileBtn = new ProfileButton();
		profileBtn.setBackground(new Color(173, 216, 230));
		profileBtn.setBounds(10, 23, 138, 118);
		profileBtn.setActionCommand("Change Pic");
		profileBtn.addActionListener(acGUI);

		panelProfile.add(profileBtn);

		textName = new JTextField();
		textName.setEditable(false);
		textName.setHorizontalAlignment(SwingConstants.CENTER);
		textName.setText("Bonix");
		textName.setBounds(10, 149, 138, 52);
		textName.putClientProperty("Quaqua.showNonEditableCaret", true);
		panelProfile.add(textName);
		textName.setColumns(10);

		leftPanel.add(panelProfile);
	}

	public void addOptionPanel(){
		JPanel optionPanel = new JPanel();
		optionPanel.setBorder(new TitledBorder(null, "Options", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		optionPanel.setBounds(10, 310, 158, 207);
		leftPanel.add(optionPanel);
		optionPanel.setLayout(null);

		btnStart = new JButton("START");
		btnStart.setBounds(26, 42, 89, 67);
		btnStart.addActionListener(this);
		optionPanel.add(btnStart);

		btnStop = new JButton("STOP");
		btnStop.setEnabled(false);
		btnStop.setBounds(26, 120, 89, 67);
		btnStop.addActionListener(acGUI);

		optionPanel.add(btnStop);
	}

// CENTER PANEL ----------------------------------------------------------------------------------------------------------------------------------------
	public void addDiscussionPanel(){
		JPanel panel = new JPanel();
		panel.setBackground(SystemColor.inactiveCaption);
		panel.setBounds(10, 11, 583, 440);
		panel.setOpaque(true);
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Discussions", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(255, 255, 255)));
		panel.setLayout(new BorderLayout(0, 0));

		panelDiscussion = new JPanel();
		panelDiscussion.setLayout(new GridBagLayout());
		panelDiscussion.setOpaque(true);
		panelDiscussion.setBackground(Color.WHITE);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		scrollPane.setViewportView(panelDiscussion);

		panel.add(scrollPane, BorderLayout.CENTER);
		centerPanel.add(panel);

	}

	public void addMsgPanel(){
		JPanel panelInput = new JPanel();
		panelInput.setOpaque(true);
		panelInput.setBounds(10, 456, 489, 65);
		panelInput.setLayout(new BorderLayout(0, 0));

		Editor editor = new Editor();
		editor.setOpaque(true);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setViewportView(editor);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		panelInput.add(scrollPane, BorderLayout.CENTER);

		centerPanel.add(panelInput);
	}

	public void addSendMsgPanel(){
		JPanel sendMsgPanel = new JPanel();
		sendMsgPanel.setBounds(503, 457, 90, 64);
		sendMsgPanel.setOpaque(true);
		centerPanel.add(sendMsgPanel);
		sendMsgPanel.setLayout(null);

		JButton btnSend = new JButton("SEND");
		btnSend.setBounds(0, 0, 89, 64);
		btnSend.addActionListener(acConnection);
		btnSend.putClientProperty("Quaqua.Button.style", "bevel");
		sendMsgPanel.add(btnSend);
	}

// RIGHT PANEL ------------------------------------------------------------------------------------------------------------------------------------------
	public void addCurrentProjectPanel(){
		JPanel currentProjectPanel = new JPanel();
		currentProjectPanel.setBorder(new TitledBorder(null, "Current Project", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		currentProjectPanel.setBounds(5, 11, 193, 55);
		rightPanel.add(currentProjectPanel);
		currentProjectPanel.setLayout(null);

		JLabel lblCurrProj = new JLabel("Project");
		lblCurrProj.setHorizontalAlignment(SwingConstants.CENTER);
		lblCurrProj.setBounds(10, 25, 173, 20);
		currentProjectPanel.add(lblCurrProj);
	}

	public void addSelectionTab(){
		selectionTabPane = new JTabbedPane(JTabbedPane.TOP);
		selectionTabPane.setBounds(5, 66, 193, 462);
		selectionTabPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		selectionTabPane.putClientProperty("Quaqua.TabbedPane.shortenTabs", Boolean.FALSE);
		rightPanel.add(selectionTabPane);
	}

	public void addProjectTab(){
		JPanel projectTab = new JPanel();
		projectTab.setLayout(null);
		selectionTabPane.addTab("Projects", null, projectTab, null);


		JPanel projectListHolder = new JPanel();
		projectListHolder.setBounds(0, 0, 183, 333);
		projectListHolder.setBorder(new TitledBorder(null, "PROJECTS", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		projectListHolder.setLayout(new BorderLayout(0, 0));
		projectListHolder.setOpaque(true);

		projectListModel = new DefaultListModel<>();

		for(Project x : allProject){
			if(x.getStatus().equalsIgnoreCase("ONGOING")){
				projectListModel.addElement(x.getProjectName());
				ongoingProject.add(x);
			}else{
				completedProject.add(x);
			}
		}

		projectList = new JList<>();
		projectList.setFont(new Font("Tempus Sans ITC", Font.PLAIN, 15));
		projectList.setModel(projectListModel);
		projectList.setSelectedIndex(-1);
		projectList.setVisibleRowCount(0);
		projectList.setValueIsAdjusting(true);
		projectList.setLocation(0,0);
		projectList.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		projectList.putClientProperty( "Quaqua.List.style", "striped");

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportView(projectList);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		projectListHolder.add(scrollPane, BorderLayout.CENTER);

		JPanel projOptionPanel = new JPanel();
		projOptionPanel.setBounds(0, 333, 183, 101);
		projectTab.add(projOptionPanel);
		projOptionPanel.setLayout(null);

		JLabel lblOption = new JLabel("Option:");
		lblOption.setBounds(0, 0, 58, 14);
		projOptionPanel.add(lblOption);

		btnCompleted = new JButton("Completed");
		btnCompleted.setBounds(90, 15, 93, 25);
		btnCompleted.putClientProperty("Quaqua.Button.style", "bevel");
		btnCompleted.addActionListener(acGUI);
		projOptionPanel.add(btnCompleted);

		btnOnGoing = new JButton("On going");
		btnOnGoing.setBounds(0, 15, 92, 25);
		btnOnGoing.putClientProperty("Quaqua.Button.style", "bevel");
		btnOnGoing.addActionListener(acGUI);
		btnOnGoing.setEnabled(false);
		projOptionPanel.add(btnOnGoing);

		JButton btnNew = new JButton("NEW");
		btnNew.setActionCommand("NEW PROJECT");
		btnNew.setBounds(0, 37, 183, 25);
		btnNew.putClientProperty("Quaqua.Button.style", "bevel");
		btnNew.addActionListener(acGUI);
		projOptionPanel.add(btnNew);

		JButton btnAssignLeader = new JButton("Assign Leader");
		btnAssignLeader.setBounds(0, 56, 183, 25);
		btnAssignLeader.putClientProperty("Quaqua.Button.style", "bevel");
		btnAssignLeader.addActionListener(acGUI);
		projOptionPanel.add(btnAssignLeader);

		JButton btnDelete = new JButton("DELETE");
		btnDelete.setActionCommand("DELETE PROJECT");
		btnDelete.setBounds(0, 75, 183, 24);
		btnDelete.putClientProperty("Quaqua.Button.style", "bevel");
		btnDelete.addActionListener(acGUI);
		projOptionPanel.add(btnDelete);

		projectTab.add(projectListHolder);
	}

	public void addUsersTab(){
		JPanel usersTab = new JPanel();
		usersTab.setLayout(null);
		selectionTabPane.addTab("Users", null, usersTab, null);

		JPanel usersListHolder = new JPanel();
		usersListHolder.setBounds(0, 0, 183, 356);
		usersListHolder.setBorder(new TitledBorder(null, "USERS", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		usersListHolder.setLayout(new BorderLayout(0, 0));
		usersListHolder.setOpaque(true);

		usersListModel = new DefaultListModel<>();
		for(Member x : allMember){
			if(x.getUserName() != null & x.getPassword() != null & x.getStatus() != null & x.getDateAdded() != null){
				usersListModel.addElement(x.getUserName());
			}
		}

		usersList = new JList<>();
		usersList.setFont(new Font("Tempus Sans ITC", Font.PLAIN, 15));
		usersList.setModel(usersListModel);
		usersList.setSelectedIndex(-1);
		usersList.setVisibleRowCount(0);
		usersList.setValueIsAdjusting(true);
		usersList.setLocation(0,0);
		usersList.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		usersList.putClientProperty( "Quaqua.List.style", "striped");

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportView(usersList);
		scrollPane.setBorder(new EmptyBorder(0,0,0,0));
		usersListHolder.add(scrollPane, BorderLayout.CENTER);

		JPanel usersOptionPanel = new JPanel();
		usersOptionPanel.setBounds(0, 360, 188, 74);
		usersTab.add(usersOptionPanel);
		usersOptionPanel.setLayout(null);

		JLabel lblOption_1 = new JLabel("Option:");
		lblOption_1.setBounds(0, 0, 99, 14);
		usersOptionPanel.add(lblOption_1);

		JButton btnAdd = new JButton("ADD");
		btnAdd.setActionCommand("ADD USER");
		btnAdd.setBounds(0, 11, 188, 36);
		btnAdd.putClientProperty("Quaqua.Button.style", "bevel");
		btnAdd.addActionListener(acGUI);
		usersOptionPanel.add(btnAdd);

		JButton btnDelete = new JButton("UPDATE");
		btnDelete.setActionCommand("UPDATE USER");
		btnDelete.setBounds(0, 42, 188, 30);
		btnDelete.putClientProperty("Quaqua.Button.style", "bevel");
		btnDelete.addActionListener(acGUI);
		usersOptionPanel.add(btnDelete);

		usersTab.add(usersListHolder);
	}
// LOOK N' FEEL ----------------------------------------------------------------------------------------------------------------------
	public static void setLookAndFeel(){
		   System.setProperty("Quaqua.tabLayoutPolicy", "wrap");
		    if (!System.getProperty("os.name").toLowerCase().startsWith("mac") && !System.getProperty("os.name").toLowerCase().startsWith("darwin")) {
		      try {
		        Methods.invokeStatic(JFrame.class, "setDefaultLookAndFeelDecorated", Boolean.TYPE, Boolean.TRUE);
		        Methods.invokeStatic(JDialog.class, "setDefaultLookAndFeelDecorated", Boolean.TYPE, Boolean.TRUE);
		      }
		      catch (NoSuchMethodException e) {
		        e.printStackTrace();
		      }
		    }
		    try {
		      UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
		    }
		    catch (Exception e) {
		      e.printStackTrace();
		    }
	}


	public static void main(String[] args){
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					setLookAndFeel();
					new ServerGUI();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent btn) {
		String cmd = btn.getActionCommand();

		if(cmd.equalsIgnoreCase("START")){
			try {
				serverLogic = new ServerLogic(this);
			} catch (Exception e) {e.printStackTrace();}
			new ServerRunning().start();
			btnStop.setEnabled(true);
			btnStart.setEnabled(false);
		}

	}

// ACTIONLISTENER ------------------------------------------------------------------------------------------------------------------
	public class ActionGUI implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent btn) {
			String cmd = btn.getActionCommand();

// USER ----------------------------------------------------------------------------------------------------------------------------
			if(cmd.equalsIgnoreCase("ADD USER")){
				new AddUserGUI();
			}

			if(cmd.equalsIgnoreCase("UPDATE USER")){
				if(usersList.getSelectedIndex() >= 0){
					new UpdateUserGUI(allMember.get(usersList.getSelectedIndex()));
				}else{
					JOptionPane.showMessageDialog(null, "Please Select a User");
				}

			}


